package com.retlife.tvshow.ui

import android.app.AlertDialog
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.KeyEvent
import android.view.LayoutInflater
import android.widget.Button
import android.widget.TextView
import com.retlife.tvshow.R
import com.retlife.tvshow.global.EventBusMsg
import com.retlife.tvshow.global.EventBusOrder.Companion.ACTION_CONFIRM
import org.greenrobot.eventbus.EventBus

class InitDialog(context: Context) {
    private val dialog: AlertDialog
    private var maxCount = 8
    private val tv: TextView
    private var btnUp: Button
    private var btnDown: Button

    init {
        val builder = AlertDialog.Builder(context)
        val view = LayoutInflater.from(context).inflate(R.layout.dialog_init, null)
        builder.setView(view)
        dialog = builder.create()
        dialog.setCanceledOnTouchOutside(false)
        dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        tv = view.findViewById(R.id.tv_max_connect_count)
        btnUp = view.findViewById(R.id.btn_up)
        btnUp.setOnClickListener {
            if (maxCount < 8) {
                maxCount++
                tv.text = maxCount.toString()
            }
        }
        btnDown = view.findViewById(R.id.btn_down)
        btnDown.setOnClickListener {
            if (maxCount >= 2) {
                maxCount--
                tv.text = maxCount.toString()
            }
        }
        view.findViewById<Button>(R.id.btn_confirm).setOnClickListener {
            EventBus.getDefault().post(EventBusMsg(ACTION_CONFIRM, maxCount))
            dismiss()
        }
        dialog.setOnKeyListener { _, keyCode, event ->
            if (event.action == KeyEvent.ACTION_DOWN) {
                when (keyCode) {


                    KeyEvent.KEYCODE_DPAD_UP -> {
                       pressUp()
                        return@setOnKeyListener true
                    }

                    KeyEvent.KEYCODE_DPAD_DOWN -> {
                        pressDown()
                        return@setOnKeyListener true
                    }
                }
            }
            false
        }
    }

    fun show() {
        dialog.show()
    }

    fun dismiss() {
        dialog.dismiss()
    }

    fun isVisible(): Boolean {
        return dialog.isShowing
    }

    fun destroy() {
    }

    fun getCount(): Int {
        return maxCount
    }

    private fun pressUp() {
        btnUp.performClick()
    }

    private fun pressDown() {
        btnDown.performClick()
    }
}